package com.springboot.test.concurrent;

import java.util.concurrent.TimeUnit;

public class Volatile{
    public static void main(String[] args){
        testVolatile();
    }
    
    public static void testVolatile(){
       Test test = new Test();
        //第一个线程
        new Thread(() -> { System.out.println(Thread.currentThread().getName() + "\t first thread");
            try {
                //暂停3s
                TimeUnit.SECONDS.sleep(3);
                test.changeNum();
         		System.out.println(Thread.currentThread().getName() + "\t current value:" + test.n);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "threadAAA").start();
        //第二个线程是main线程
        while (test.n == 0) {
            //如果myData的num一直为零，main线程一直在这里循环
//			System.out.println(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t now value:" + test.n);
    }
}
class Test{
    int n = 0; //没有加volatile 不保证可见性
//    volatile int n = 0; //保证可见性
    public void changeNum(){
        this.n = 1;
    }
}
